package com.skydonkey.service;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.processing.OperationManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import com.skydonkey.config.RabbitConfig;
import com.skydonkey.pojo.dto.VideoSampleDto;
import com.skydonkey.pojo.po.VideoSamplesFailed;
import com.skydonkey.utils.QiniuUtils;
import com.sun.jmx.snmp.SnmpUnknownAccContrModelException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;

import java.io.IOException;

@Service
public class VideoSampleListener {

    private static final Logger log = LoggerFactory.getLogger(VideoSampleListener.class);
    private static final Integer SAMPLE_COUNT = 10;
    private static final Integer MAX_TRY_TIMES = 2; //尝试向七牛提交请求三次以上仍然失败的话作记录


    @Autowired
    QiniuUtils qiniuUtils;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    VideoSampleService videoSampleService;

//    // 检查mp4到flv消息队列中是否有消息, 有则取出来轮询, 然后判断是否更新视频的新的flv地址。
//    @RabbitListener(queues = RabbitConfig.CONVERSION_FLV_QUEUE_NAME, ackMode = "MANUAL")
//    public void checkConvertVideo(VideoConversionDto videoData, Channel channel, Message message) {
//        log.info(videoData.toString());
//        OperationStatus status = null;
//        try {
//            status = qiniuUtils.queryStatus(videoData.getPersistId());
//        } catch (QiniuException e) {
//            e.printStackTrace();
//            log.error("query persistId:[" + videoData.getPersistId() + "] from qiniu error: " +
//                    e.getMessage());
//            // 发生错误，拒绝消息, 记录日志, 放回队列
//            try {
//                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
//            } catch (IOException ioException) {
//                ioException.printStackTrace();
//                log.error("reject message error: " + e.getMessage());
//                return;
//            }
//        }
//        if (status == null) {
//            log.error("No status found for this persistId.");
//            return;
//        }
//        switch (status.code) {
//            case 0:
//                log.info("The operation is waiting in queue."); break;
//            case 1:
//                log.info("The ope   ration is processing.");break;
//            case 2:
//                log.info("The operation is completed successfully.");break;
//            case 3:
//                log.info("The operation failed. Reason: " + status.desc);break;
//            default:
//                log.info("Unknown status.");break;
//        }
//        if(status.code != videoData.getStatusCode()){
//            //状态发生改变, 同步数据库
//            videoData.setStatusCode(status.code);
//        }
//        // 如果处理成功，确认消息
//        try {
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//            rabbitTemplate.convertAndSend(
//                    RabbitConfig.CONVERSION_EXCHANGE_NAME,
//                    RabbitConfig.CONVERSION_MP4_TO_FLV_ROUTING_KEY,
//                    videoData);
//        } catch (IOException e) {
//            e.printStackTrace();
//            log.info("ack message failed for persistId[" + videoData.getPersistId() + "]");
//        }
//    }

    public void generateSample(Long videoId, String videoKey, int count){
        Configuration cfg = new Configuration();
        String accessKey = qiniuUtils.getQiniuProperties().getAccessKey();
        String secretKey = qiniuUtils.getQiniuProperties().getSecretKey();
        String bucket = qiniuUtils.getQiniuProperties().getBucket();
        String notifyURL = qiniuUtils.getQiniuProperties().getNotifyURL();
        Auth auth = Auth.create(accessKey, secretKey);
        OperationManager operationManager = new OperationManager (auth, cfg);
        //构建保存的图片名字
        String newKey = videoKey.substring(0, videoKey.lastIndexOf('.'));
        String saveMp4Entry = UrlSafeBase64.encodeToString( newKey + "-$(count)" + ".png");
        String fops = "vsample/png/frames/" + SAMPLE_COUNT + "/s/480x360/pattern/" + saveMp4Entry;
        StringMap params = new StringMap().putWhen("force", 1, true)
                .putNotNull("notifyURL", notifyURL);
        try {
            String persistId = operationManager.pfop(bucket, videoKey, fops, params);
            // 返回persistentId，可以用来查询操作的状态
            if (persistId == null) {
                // 记录错误
                log.info("生成采帧缩略图失败");
                VideoSamplesFailed failed = new VideoSamplesFailed()
                        .setVideoId(videoId)
                        .setError("persistId is null!");
                videoSampleService.addVideoFailed(failed);
            }

        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时简单状态信息
            VideoSamplesFailed failed = new VideoSamplesFailed()
                    .setVideoId(videoId)
                    .setError(r.toString());
            videoSampleService.addVideoFailed(failed);
        }
    }

    @RabbitListener(queues = RabbitConfig.VIDEO_SAMPLE_QUEUE_NAME)
    public void videoSampleListener(VideoSampleDto videoData, Channel channel, Message message) throws IOException {
        log.info(videoData.toString());
        Configuration cfg = new Configuration();
        String accessKey = qiniuUtils.getQiniuProperties().getAccessKey();
        String secretKey = qiniuUtils.getQiniuProperties().getSecretKey();
        String bucket = qiniuUtils.getQiniuProperties().getBucket();
        String notifyURL = qiniuUtils.getQiniuProperties().getNotifyURL();
        Auth auth = Auth.create(accessKey, secretKey);
        OperationManager operationManager = new OperationManager (auth, cfg);
         //构建保存的图片名字
        String videoKey = videoData.getVideoKey();
        String newKey = videoKey.substring(0, videoKey.lastIndexOf('.'));
        String saveMp4Entry = UrlSafeBase64.encodeToString( newKey + "-$(count)" + ".png");
        String fops = "vsample/png/frames/" + SAMPLE_COUNT + "/s/480x360/pattern/" + saveMp4Entry;
        StringMap params = new StringMap().putWhen("force", 1, true)
                .putNotNull("notifyURL", notifyURL);
        try {
            String persistId = operationManager.pfop(bucket, videoKey, fops, params);
            // 返回persistentId，可以用来查询操作的状态
            if (persistId == null) {
                // 记录错误
                log.info("生成采帧缩略图失败");
                VideoSamplesFailed failed = new VideoSamplesFailed()
                        .setVideoId(videoData.getVideoId())
                        .setError("persistId is null!");
                videoSampleService.addVideoFailed(failed);
            }

        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时简单状态信息
            VideoSamplesFailed failed = new VideoSamplesFailed()
                    .setVideoId(videoData.getVideoId())
                    .setError(r.toString());
            videoSampleService.addVideoFailed(failed);
            log.info(r.bodyString());
        }

    }


}
